package server

import (
	"common/config"
	"context"
	"errors"
	"golang.org/x/crypto/bcrypt"
	"user_srv/internal/model/dao"
	pb "user_srv/proto"
)

type Server struct {
	pb.UnimplementedUserServer
}

func (Server) Register(ctx context.Context, request *pb.RegisterRequest) (*pb.RegisterResponse, error) {
	var user dao.User
	config.DB.Where("username=?", request.Username).Find(&user)
	if user.ID != 0 {
		return nil, errors.New("注册失败，用户名已存在")
	}
	password, _ := bcrypt.GenerateFromPassword([]byte(request.Password), bcrypt.DefaultCost)
	users := dao.User{
		Username: request.Username,
		Password: string(password),
	}
	err := config.DB.Create(&users).Error
	if err != nil {
		return nil, errors.New("注册失败")
	}
	return &pb.RegisterResponse{Id: int64(users.ID)}, nil
}

func (Server) Login(ctx context.Context, request *pb.LoginRequest) (*pb.LoginResponse, error) {
	var user dao.User
	config.DB.Where("username=?", request.Username).Find(&user)
	if user.ID == 0 {
		return nil, errors.New("登录失败，用户名不正确")
	}
	err := bcrypt.CompareHashAndPassword([]byte(user.Password), []byte(request.Password))
	if err != nil {
		return nil, errors.New("登录失败，密码错误")
	}
	return &pb.LoginResponse{Id: int64(user.ID)}, nil
}
